// pages/control.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isPress: [],
    connected: 1, //wifi是否连接到盒子。1：已连接，0：正在连接，-1：未连接
    successAudio: {},
    failAudio: {},
    app: getApp(),
    lastConnectState: -1, //上一次的连接状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var innerAudioContext1 = wx.createInnerAudioContext();
    innerAudioContext1.src = "assets/success.mp3";
    var innerAudioContext2 = wx.createInnerAudioContext();
    innerAudioContext2.src = "assets/fail.mp3";
    this.setData({
      successAudio: innerAudioContext1,
      failAudio: innerAudioContext2,
    });

    let that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        //console.log("蓝牙模块初始化成功" + res)
        that.setData({
          isBluetoothAvailable: true
        });
      },
      fail: function (res) {
        //console.log("蓝牙模块初始化失败" + res)
        that.setData({
          isBluetoothAvailable: false
        });
      },
    });
    wx.onBluetoothAdapterStateChange((result) => {
      //console.log("蓝牙适配器状态改变" + result.available);
      if (result.available) { //只要开启了蓝牙，就初始化一次
        wx.openBluetoothAdapter();
      } else {
        wx.showToast({
          title: '蓝牙已关闭',
        });
      }
      that.setData({
        isBluetoothAvailable: result.available
      });
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //console.log("onshow");
    let that = this;
    that.setData({
      connected: 0,
      showStatus: true,
      app: getApp()
    });
    this.getAction("/v1/ping", function (res) {
      //console.log("ping")
      //console.log(res)
      if (res.statusCode != 200) {
        that.setData({
          connected: -1
        });
        if (getApp().globalData.mac) {
          wx.showToast({
            title: '请长按电源键开机或长按OK键添加设备',
            icon: 'none',
            duration: 5000
          })
        } else {
          wx.showToast({
            title: '请长按OK键添加设备',
            icon: 'none',
            duration: 3000
          })
        }
      } else {
        that.setData({
          connected: 1
        });
        setTimeout(() => {
          that.setData({
            showStatus: false
          });
        }, 5000);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  onShareAppMessage: function (params) {

  },
  postAction(url, data) {
    let that = this;
    wx.request({
      url: 'http://' + getApp().globalData.host + ':8080' + url,
      method: 'POST',
      data: data,
      headers: {
        'content-type': 'application/json ;charset=utf-8' //默认值
      },
      timeout: 5000,
      dataType: 'json',
      success: function (res) {
        //console.log(res)
        that.setData({
          connected: res.statusCode === 200 ? 1 : -1,
        })
      },
      fail: function (res) {
        that.setData({
          connected: -1,
          showStatus: true
        })
      },
    });
  },
  getAction(url, callback) {
    wx.request({
      url: 'http://' + getApp().globalData.host + ':8080' + url,
      method: 'GET',
      complete: callback,
      timeout: 5000,
    })
  },
  onSendShortSingal() {
    if (getApp().globalData.isVibrateOn) {
      wx.vibrateShort();
    };

    if (getApp().globalData.isSoundOn) {
      if (this.data.connected != 1) {
        this.data.failAudio.play();
      } else {
        this.data.successAudio.play();
      }
    }
  },
  sendKeyCode: function (e) {
    this.onSendShortSingal();
    var keycode = this.getKeyCodeByTagId(e.target.id);
    this.postAction('/v1/keyevent', {
      keycode: keycode,
      longclick: false
    });
  },
  onSendLongSingal() {
    if (getApp().globalData.isVibrateOn) {
      wx.vibrateLong();
    }
    if (getApp().globalData.isSoundOn) {
      this.data.successAudio.play();
    }
  },
  onKeyLongTap: function (e) {
    //console.log(e)
    if (e.target.id == "ok") { //长按OK跳转到APP设置
      wx.navigateTo({
        url: '../setting/setting'
      });
      return;
    }
    this.onSendLongSingal(); //发声震动
    if (e.target.id === "menu") { //长按菜单打开TV设置
      var action = "setting";
      this.postAction("/v1/action", {
        action
      });
      return;
    } else if (e.target.id === 'home') { //长按房子键打开电视管家
      var action = "openclear";
      this.postAction("/v1/action", {
        action
      });
      return;
    } else if (e.target.id === "power") {
      this.connectBLEDevice();
      return;
    }
    //长按其他键
    var keycode = this.getKeyCodeByTagId(e.target.id);
    this.postAction("/v1/keyevent", {
      keycode: keycode,
      longclick: true
    });
    this.afterLongTap();
  },
  onTouchDown: function (e) {
    //console.log("触摸按下");
    switch (e.currentTarget.id) {
      case "up":
        this.setData({
          isPress: [!0, !1, !1, !1, !1]
        });
        break;

      case "down":
        this.setData({
          isPress: [!1, !1, !1, !1, !0]
        });
        break;

      case "left":
        this.setData({
          isPress: [!1, !0, !1, !1, !1]
        });
        break;

      case "right":
        this.setData({
          isPress: [!1, !1, !1, !0, !1]
        });
        break;

      case "ok":
        this.setData({
          isPress: [!1, !1, !0, !1, !1]
        });
        break;

      case "back":
        this.setData({
          backpressed: !0
        });
        break;

      case "focus-for":
        this.setData({
          focusforpressed: !0
        });
        break;

      case "focus-back":
        this.setData({
          focusbackpressed: !0
        });
        break;

      case "volume-down":
        this.setData({
          volumedownpressed: !0
        });
        break;

      case "mute":
        this.setData({
          mutepressed: !0
        });
        break;

      case "volume-up":
        this.setData({
          volumeuppressed: !0
        });
        break;

      case "power":
        this.setData({
          powerpressed: !0
        });
        break;

      case "home":
        this.setData({
          homepressed: !0
        });
        break;

      case "menu":
        this.setData({
          menupressed: !0
        });
    }
  },
  onTouchUp: function (e) {
    //console.log("触摸抬起")
    let that = this;
    setTimeout(function () {
      that.setData({
        isPress: [!1, !1, !1, !1, !1],
        backpressed: !1,
        focusforpressed: !1,
        focusbackpressed: !1,
        menupressed: !1,
        homepressed: !1,
        powerpressed: !1,
        volumeuppressed: !1,
        mutepressed: !1,
        volumedownpressed: !1
      });
    }, 300); //移动端web有300ms的延时，抬起太快看不到按键效果
  },
  //获取本机蓝牙开关状态
  openBluetoothAdapter() {
    let that = this;
    wx.openBluetoothAdapter({
      success: res => {
        //console.log("蓝牙初始化成功！");
      },
      fail: error => {
        wx.showToast({
          title: '蓝牙未开启，无法开机',
          icon: 'none'
        })
      },
    });
  },
  //连接设备
  connectBLEDevice() {
    let that = this;
    //console.log(getApp().globalData.mac)
    if (!that.data.isBluetoothAvailable) {
      wx.showToast({
        title: '蓝牙未开启，无法开机',
        icon: 'none'
      });
      return;
    }
    wx.makeBluetoothPair({
      deviceId: getApp().globalData.mac,
      pin: 'NjM3ODY1',
      timeout: 3,
      success: function (res) {
        wx.showToast({
          title: '取消蓝牙配对后才能开机',
          icon: 'none'
        });
      }
    })
    /*
    wx.createBLEConnection
    ({
      deviceId: getApp().globalData.mac,
      //timeout: 3000,
      success: res => {
        //console.log("蓝牙连接成功！");
        //console.log(getApp().globalData.mac)
        that.disconnectBLEDevice(); //连接后就断开
      },
      fail: error => {
        //console.log(getApp().globalData.mac)
        //console.log(JSON.stringify(error));
      },
    });*/
  },
  //断开连接
  disconnectBLEDevice() {
    let that = this;
    wx.closeBLEConnection({
      deviceId: getApp().globalData.mac,
      success: () => {
        //console.log("断开连接成功！");
      },
      fail: error => {
        //console.log(JSON.stringify(error));
      },
    });
  },
  getKeyCodeByTagId(id) {
    var keycode = 0;
    switch (id) {
      case "power":
        keycode = 26;
        break;

      case "home":
        keycode = 3;
        break;

      case "menu":
        keycode = 82;
        break;

      case "up":
        keycode = 19;
        break;

      case "down":
        keycode = 20;
        break;

      case "left":
        keycode = 21;
        break;

      case "right":
        keycode = 22;
        break;

      case "ok":
        keycode = 23;
        break;

      case "volume-down":
        keycode = 25;
        break;

      case "mute":
        keycode = 164;
        break;

      case "volume-up":
        keycode = 24;
        break;

      case "back":
        keycode = 4;
        break;

      case "focus-back":
        keycode = 167;
        break;

      case "focus-for":
        keycode = 166;
    }
    return keycode;
  },
})